package com.example.demo.service.Impl;

import com.example.demo.exception.UserException;
import com.example.demo.model.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IuserService;
import com.example.demo.vo.UserInfoLogVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@AllArgsConstructor
public class UserServiceImpl implements IuserService {

//    @Autowired
//    private UserMapper userMapper;
    private final UserMapper userMapper;

    @Transactional
    @Override
    public void insertUser(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        User newUser = userMapper.getUserByNamePass(username, password);
        if (newUser == null) {
            userMapper.insertUser(user);
        } else {
            throw new UserException("用户已存在");
        }
    }

    @Override
    public UserInfoLogVo getUserInfo(Long userId) {
        return userMapper.getUserInfo(userId);
    }

    @Override
    public User getUserByNamePass(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            throw new Error("用户名和密码不能为空！");
        }
        return userMapper.getUserByNamePass(username, password);
    }

    ;

    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    @Transactional
    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Transactional
    @Override
    public void deleteUser(Long id) {
        userMapper.deleteUser(id);
    }
}